package com.example.textview.datastorage;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.textview.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileActivity extends AppCompatActivity implements View.OnClickListener {

    EditText et_name;
    Button btn_save,btn_show;
    TextView tv_show;
//    SharedPreferences msharedPreferences;
//    SharedPreferences.Editor meditor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);

        et_name=findViewById(R.id.et_name);
        tv_show=findViewById(R.id.tv_show);
        btn_save=findViewById(R.id.btn_save);
        btn_show=findViewById(R.id.btn_show);
        btn_save.setOnClickListener(this);
        btn_show.setOnClickListener(this);

        //MODE_PRIVATE 本应用才可以读写
       // msharedPreferences=getSharedPreferences("filename",MODE_PRIVATE);
       // meditor= msharedPreferences.edit();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId())
        {
            case R.id.btn_save:
               save(et_name.getText().toString());
                break;

            case R.id.btn_show:
                tv_show.setText(read());
                break;

        }
    }

    private void save(String content)
    {
        FileOutputStream fileOutPutStream=null;
        try {
             fileOutPutStream=openFileOutput("text.tex",MODE_PRIVATE);
            fileOutPutStream.write(content.getBytes());

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(fileOutPutStream!=null) {
                try {
                    fileOutPutStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String read(){
        FileInputStream fileInputStream=null;

        try {
            fileInputStream=openFileInput("text.tex");
            byte[] buff=new byte[1024];
            StringBuffer stringBuffer=new StringBuffer();
            int len=0;
            while ((len=fileInputStream.read(buff))>0)
            {

               stringBuffer.append(new String(buff,0,len));

            }
            return stringBuffer.toString();

        }
         catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(fileInputStream!=null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }
}